
<template>
  <div class="tob">
    <!--搜索-->
    <el-form :inline="true" class="demo-form-inline">
      <el-button type="success" size="mini" @click="handleAdd">新增角色</el-button>
      <el-button type="danger" size="mini" @click="operateList">新增菜单</el-button>
      <el-button type="primary" size="mini" @click="operateDept">新增资源</el-button>
    </el-form>
    <!--table表格-->
    <el-table ref="singleTable" :data="tableData" highlight-current-row style="width: 90%">
      <el-table-column type="index" width="55" align="center" label="序号" />
      <el-table-column property="jurisdiction" label="角色名称" prop="name" />
      <el-table-column property="phone" label="角色类型" prop="type" />
      <el-table-column property="phone" label="角色权重" prop="weight" />
      <el-table-column property="phone" label="角色描述" prop="desc" />
      <el-table-column property="operation" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="handleUpdate(scope.row.id)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row.id)">删除</el-button>
          <el-button type="text" @click="jurisdiction(scope.row.id)">分配资源</el-button>
          <el-button type="text" @click="Distribution(scope.row.id)">分配菜单</el-button>
          <el-button type="text" @click="Unpublish(scope.row.id)">取消资源</el-button>
          <!-- <el-button type="text" @click="Distribution(scope.row.id)"></el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <template>
      <el-row style="height: 60px" justify="end" class="middle">
        <!-- 放置分页组件 -->
        <el-pagination
          v-model="pageParams.currentPage"
          background
          :page-size="pageParams.pageSize"
          :total="pageParams.resultCount"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </template>
    <!-- 控制角色新增和编辑弹窗 -->
    <el-dialog width="500px" :title="title" :visible.sync="open" @close="reset">
      <el-form ref="form" label-width="120px" :model="form" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" size="small" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择角色类型">
            <el-option
              v-for="option in roleTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色权重" prop="weight">
          <el-select v-model="form.weight" placeholder="请选择角色权重">
            <el-option
              v-for="option in roleWeightOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input v-model="form.desc" type="textarea" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="submitForm">确定</el-button>
          <el-button size="mini" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配资源 -->
    <!-- 分配资源 -->
    <!-- 分配资源 -->
    <!-- 分配资源 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配资源">
      <!-- 放置资源数据 -->
      <el-tree
        ref="permTree"
        check-strictly
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 分配菜单 -->
    <!-- 分配菜单 -->
    <!-- 分配菜单 -->
    <el-dialog :visible.sync="showDialog" title="分配菜单">
      <!-- 放置资源数据 -->
      <el-tree
        ref="PermTree"
        check-strictly
        node-key="id"
        :data="permissionList"
        :props="{ label: 'name' }"
        show-checkbox
        :default-checked-keys="PermIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="confirm">确定</el-button>
          <el-button size="mini" @click="showDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 取消菜单和资源弹窗 -->
    <!-- 取消菜单和资源弹窗 -->
    <!-- 取消菜单和资源弹窗 -->
    <!-- 取消菜单和资源弹窗 -->
    <el-dialog :visible.sync="disappear" title="取消菜单">
      <div>菜单数据</div>
      <el-tree
        ref="PermTree"
        check-strictly
        node-key="id"
        :data="permissionForm"
        :props="{ label: 'name' }"
        show-checkbox
        :default-checked-keys="checkedIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini">确定</el-button>
          <el-button size="mini" @click="disappear = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { listRole, addRole, getRole, updateRole, deleteRole, allocation, assignPerm, allocationApi, assignPermAPi, countermand } from '@/api/business/role'
export default {
  data() {
    return {
      // 控制弹出层的显示和隐藏
      open: false,
      conceal: false,
      value: true,
      title: '',
      showPermissionDialog: false, // 控制分配资源弹窗显示和隐藏
      currentRoleId: null,
      permIds: [],
      permissionData: [], // 放置分配资源的数据
      roleWeightOptions: [], // 角色权重选项
      // 菜单数据
      // 菜单数据
      // 菜单数据
      // 菜单数据
      showDialog: false, // 菜单弹窗
      permissionList: [], // 放置分配菜单的数据
      menuRoleId: null,
      PermIds: [],
      // 控制取消菜单和权限的显示隐藏
      disappear: false,
      permissionForm: [],
      checkedIds: [],
      // 其他数据和状态
      // 数据范围选项
      roleTypeOptions: [
        {
          value: '1',
          label: '电工师傅'
        },
        {
          value: '2',
          label: '游客'
        },
        {
          value: '3',
          label: '超级管理员'
        }
      ],
      // 模糊查询功能
      condition: '',
      // 分页数据
      pageParams: {
        currentPage: 1,
        pageSize: 10,
        resultCount: 0
      },
      // 新增数据
      form: {},
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        weight: [
          { required: true, message: '角色权重不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ],
        merchantId: [
          { required: true, message: '商户ID不能为空', trigger: 'blur' }
        ],
        owner: [
          { required: true, message: '所有者不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ]
      },
      // 渲染数据
      tableData: [],
      timer: null // 定时器，用于实现模糊查询时的延迟搜索效果
    }
  },

  watch: {
    'form.type'(newVal) {
      if (newVal === '1') {
        this.roleWeightOptions = [
          {
            value: '1',
            label: '电工'
          }
          // 其他超级管理员的权重选项
        ]
      } else if (newVal === '2') {
        this.roleWeightOptions = [
          {
            value: '2',
            label: '游客'
          }
          // 其他部门管理员的权重选项
        ]
      } else if (newVal === '3') {
        this.roleWeightOptions = [
          {
            value: '3',
            label: '管理员'
          }
          // 其他普通员工的权重选项
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 新增弹窗
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加角色'
    },
    // 数据渲染
    async getList() {
      try {
        const res = await listRole(
          this.condition,
          this.pageParams.currentPage,
          this.pageParams.pageSize
        )
        this.tableData = res.data
        this.pageParams.currentPage = res.pageCount
        this.pageParams.pageSize = res.pageSize
        this.pageParams.resultCount = res.resultCount
      } catch (error) {
        console.error(error)
        // 处理错误，例如给用户提示错误信息
      }
    },
    // 分页变化时的处理函数
    handleCurrentChange(page) {
      this.pageParams.currentPage = page
      this.getList()
    },
    //   //确认按钮
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== '') {
            // 确认编辑
            updateRole(this.form).then(response => {
              this.$message.success('修改角色成功')
              this.pageParams.currentPage = 1
              this.open = false // 关闭弹层
              this.getList() // 刷新页面数据
            })
          } else {
            // 新增角色逻辑
            const res = addRole(this.form).then(response => {
              console.log(res)
              this.$message.success('新增角色成功')
              this.pageParams.currentPage = 1
              this.form.id = ''
              this.open = false // 关闭弹层
              this.getList() // 刷新页面数据
            })
          }
        }
      })
    },
    // 取消新增功能
    reset() {
      this.form = {
        name: '',
        type: '',
        weight: '',
        desc: '',
        merchantId: '',
        owner: '',
        id: ''
        // 表单验证
      }
    },

    // 角色列表编辑功能
    async handleUpdate(id) {
      this.title = '修改角色'
      const res = await getRole(id)
      this.form = res
      this.open = true
    },
    // 判断角色类型
    roleType(type) {
      if (type === '1') {
        return '超级管理员'
      } else if (type === '2') {
        return '部门管理员'
      } else {
        return '普通员工'
      }
    },
    // 删除角色
    async handleDelete(id) {
      await deleteRole(id) // 后端删除
      this.$message.success('删除角色成功')
      this.pageParams.currentPage = 1
      this.getList()
    },
    // 控制角色资源和菜单管理功能
    operateDept() {
      this.$router.push({ path: '/business/resource' })
    },
    operateList() {
      this.$router.push({ path: '/business/menu' })
    },
    // 分配资源页面
    async jurisdiction(id) {
      // 获取资源数据列表
      const res = await allocation()
      this.permissionData = res
      // 记录当前点击的id 因为后边 确定取消要存取给对应的用户
      this.currentRoleId = id
      const ref = await getRole(id)
      this.permIds = ref.id.split(',')
      console.log(this.permIds)
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      await assignPerm({
        roleId: this.currentRoleId,
        resIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('分配资源成功')
      this.showPermissionDialog = false
    },
    // 分配菜单
    // 分配菜单
    // 分配菜单
    async Distribution(id) {
      // 获取菜单数据列表
      const res = await allocationApi()
      this.permissionList = res
      this.menuRoleId = id
      const ref = await getRole(id)
      console.log(ref)
      this.PermIds = ref.id.split(',')
      console.log(this.PermIds)
      this.showDialog = true
    },
    // 提交分配菜单
    async confirm() {
      await assignPermAPi({
        roleId: this.menuRoleId,
        menuIds: this.$refs.PermTree.getCheckedKeys()
      })
      this.$message.success('分配菜单成功')
      this.showDialog = false
    },
    // 取消菜单和资源
    // 取消菜单和资源
    // 取消菜单和资源
    // 取消菜单和资源
    async  Unpublish(id) {
      console.log(id)
      const res = await countermand(id)
      console.log(res)
      this.permissionForm = res.menuTreeVOList
      console.log('222', res.menuIdList)
      this.checkedIds = JSON.parse(res.menuIdList)
      console.log('12112', this.checkedIds)
      this.disappear = true
    }
  }
}
</script>
<style lang="scss" scoped>
.tob {
  width: 100vw;
  height: 100vh;
}
// 搜索框
.demo-form-inline {
  margin: 20px;
}

.input {
  width: 300px;
  margin-right: 30px;
}
.paging {
  text-align: center;
  margin-top: 20px;
}
.middle {
  text-align: center;
  margin-top: 30px;
}
</style>
